import random

import time


import requests
import urllib.request
import demjson
import re

user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5)'
headers = {'User-Agent': user_agent}
session = requests.session()

def getAsleep():
    sleepTime = random.uniform(0, 2)
    # print("休眠：", sleepTime)
    time.sleep(sleepTime)

def downAFile(fileName ,fileUrl ,downCallBack):
    downPath = 'F:\\小伊\\网易轻松一刻\\%s.m4a'%(fileName)
    print("正在下载：" ,fileName)
    urllib.request.urlretrieve(fileUrl, downPath ,downCallBack)

def downCallBack(downedCount, countSize, allSize):
    per = 100.0 * downedCount * countSize / allSize
    if per > 100:
        per = 100
    print('下载进度：  %.2f%%' % per)


def getUrlData( url ):
    page = session.get(url, headers=headers)
    jsonData = page.text

    bean1 = demjson.decode(jsonData)
    bean2 = bean1['data']
    # print(bean2)
    for bean3 in bean2:
        name = bean3["name"]
        # 去除标题中的特殊字符
        name = re.sub("[\s+\.\!\/_,$%^*(+\"\']+|[+——！，。?|？、~@#￥%……&*（）]+", "", name)

        update_time =bean3["update_time"].split(" ")[0]
        file_path= bean3["file_path"]
        downUrl="http://od.qingting.fm/%s"%(file_path)

        fileName ="%s %s"%(update_time,name)
        # print(  "  ", fileName)
        downAFile(fileName ,downUrl ,downCallBack)



    # bean3 = bean2['tracksAudioPlay']
    # # print(bean3)
    # for data in bean3:
    #  name = data['trackName']
    #  if  "数鸭子" in name:
    #      i=1
    #      # print("不符合要求： " ,name)
    #  elif  "我不上你的" in name:
    #      i = 1
    #  elif "小兔子乖乖" in name:
    #      i =1
    #  else:
    #      # print("-->" ,name)
    #      arrays= name.split("-")
    #      # print(url)
    #      # if len(arrays)>1:
    #      # name =arrays[1]
    #      # name = name.strip('》')
    #      # name = name.strip('《')
    #      # if len(arrays)< 2:
    #      #     arrays = name.split(" ")
    #      # name = arrays[len(arrays)-1]
    #      src = data['src']
    #      print( name , "->" ,src)
    #      downAFile(name ,src ,downCallBack)

index = 1
sum = 31

while index <= sum:
    url= "http://i.qingting.fm/wapi/channels/81984/programs/page/%d"%(index)
    # print(url)
    getUrlData(url)
    index =index +1
    getAsleep()




